package lumis.portal.sendmail;

import lumis.util.log.ILogger;
import lumis.util.log.LoggerFactory;

/**
 * For each run, this thread processes a single mail pending in the queue it was
 * assigned for.
 * 
 * @version $Revision: 6251 $ $Date: 2007-03-27 10:49:29 -0300 (Tue, 27 Mar 2007) $
 * @since 4.0.4
 */
class SendMailThread extends Thread
{
	/** System logger for this class. */
	private static ILogger logger = LoggerFactory.getLogger(SendMailThread.class);

	/**
	 * The id of the mail queue this thread is assigned for.
	 * 
	 * @since 4.0.4
	 */
	private final String queueId;

	/**
	 * @see #hasProcessedQueuedMail()
	 * @since 4.0.4
	 */
	private boolean processedQueuedMail = false;

	/**
	 * Instance for the thread's callback operations.
	 * 
	 * @since 4.0.4
	 */
	private final IMailQueueProcessThreadCallback callback;

	/**
	 * Creates a SendMailThread to process the specified mail queue.
	 * 
	 * @param callback
	 *            instance for the thread's callback operations.
	 * @param queueId
	 *            the mail queue's id.
	 * @see #run()
	 * @since 4.0.4
	 */
	public SendMailThread(IMailQueueProcessThreadCallback callback, String queueId)
	{
		super("SendMailThread-" + queueId);
		this.callback = callback;
		this.queueId = queueId;
		setPriority(Thread.MIN_PRIORITY);
	}

	/**
	 * Processes the next queued mail for the queue.
	 * 
	 * @since 4.0.4
	 */
	@Override
	public void run()
	{
		try
		{
			processedQueuedMail = callback.processNextQueuedMail(queueId);
		}
		catch (Exception e)
		{
			logger.error("Error while processing queued mail", e);
		}
	}

	/**
	 * Indicates if this thread has processed a queued mail.
	 * 
	 * @return true if this thread has processed a queued mail, false otherwise.
	 * @since 4.0.4
	 */
	public boolean hasProcessedQueuedMail()
	{
		return processedQueuedMail;
	}
}
